package com.hzhr.iot.meterplan.service;

import com.hzhr.iot.core.annotation.ApiImplicitInternalParams;
import com.hzhr.iot.core.exception.ServiceException;
import com.hzhr.iot.core.util.HzhrTypeUtil;
import com.hzhr.iot.meterplan.constant.Meterplan_ErrorsEnum;
import com.hzhr.iot.meterplan.dao.mapper.generator.ChaobiaogongdanEntityMapper;
import com.hzhr.iot.meterplan.dao.mapper.generator.custom.ChaobiaogongdanEntityCustomMapper;
import com.hzhr.iot.meterplan.dao.mapper.generator.custom.CygMapper;
import com.hzhr.iot.meterplan.dao.mapper.generator.custom.RuhujihuaEntityCustomMapper;
import com.hzhr.iot.meterplan.entity.ext.ChaobiaogongdanEntityExt;
import com.hzhr.iot.meterplan.entity.ext.RuhujihuaEntityExt;
import com.hzhr.iot.meterplan.model.meterPlan_publish.MeterPlan_PublishGetModel;
import com.hzhr.iot.meterplan.model.meterPlan_publish.MeterPlan_PublishModel;
import com.hzhr.iot.meterplan.model.meterPlan_publish.MeterPlan_PublishPostModel;
import com.hzhr.iot.meterplan.model.meterPlan_publish.WordOrder;
import com.hzhr.iot.meterplan.service.base.BaseService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class MeterPlan_PublishService extends BaseService {

    @Autowired
    RuhujihuaEntityCustomMapper ruhujihuaEntityCustomMapper;

    @Autowired
    ChaobiaogongdanEntityCustomMapper chaobiaogongdanEntityCustomMapper;

    @Autowired
    ChaobiaogongdanEntityMapper chaobiaogongdanEntityMapper;

    @Autowired
    CygMapper cygMapper;

    //region javadoc注释 : post
    /**
     * 发布 <br/><br/>
     * 1.查询抄表计划： <br/>
     *  如果抄表计划不存在，抛出异常“抄表计划不存在”； <br/>
     * 2.验证抄表计划下的抄表册： <br/>
     *  如果该抄表计划下不存在状态为“待抄表”或“待复抄”的抄表册，抛出异常“抄表册已经完成录入，无法发布数据” <br/>
     * 3.发布数据： <br/>
     *  根据WorkOrder.id找到该抄表计划下的状态为“待抄表”或“待审核”的抄表工单，如果抄表工单存在，则根据WorkOrder.collectData发布数据， <br/>
     *  注意：如果本次表底数大于或等于上次表底数，则发布数据，否则不发布。 <br/>
     * 4.返回信息； <br/>
     * @param header <br/>
     * _token : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 令牌;<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : true;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : string;<br/>
     * _hzhr-user-id : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 用户编号;<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : true;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : int;<br/>
     * _hzhr-user-code : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 用户代码;<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : true;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : string;<br/>
     * _hzhr-user-name : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 用户名;<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : true;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : string;<br/>
     * _hzhr-company-id : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 公司编号;<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : true;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : int;<br/>
     * _hzhr-dept-id : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 部门编号;<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : true;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : int;<br/>
     * _hzhr-user-type : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 用户类型(关联: common_service.options.code, typeCode = 'USER_TYPE');<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : true;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : string;<br/>
     * _hzhr-transaction-id : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 交易流水号;<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : true;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : string;<br/>
     * _hzhr-transaction-type : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 交易类型;<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : true;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : string;<br/>
     * _hzhr-access-mode : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 访问模式 0:一般 1:全局;<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : false;<br/>&nbsp&nbsp&nbsp&nbsp 默认值 : 0;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : int;<br/><br/>
     * @param query <br/>
     * _show : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 展示形式 one:展示一个,list:展示列表,null(空值):不展示;<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : false;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : string;<br/>
     * _show_info : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 是否展示详情;<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : false;<br/>&nbsp&nbsp&nbsp&nbsp 默认值 : false;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : boolean;<br/><br/>
     * @param meterPlanId 抄表计划id <br/><br/>
     * @param body <br/><br/>
     * @throws ServiceException <br/>
     * METERPLAN_PUBLISHSERVICE_POST_201 : <br/>&nbsp&nbsp&nbsp&nbsp异常类型 : 业务流程异常<br/>&nbsp&nbsp&nbsp&nbsp异常业务 : 查询抄表计划状态<br/>&nbsp&nbsp&nbsp&nbsp异常描述 : 抄表计划不存在<br/>
     * METERPLAN_PUBLISHSERVICE_POST_202 : <br/>&nbsp&nbsp&nbsp&nbsp异常类型 : 业务流程异常<br/>&nbsp&nbsp&nbsp&nbsp异常业务 : 验证抄表计划下的抄表册<br/>&nbsp&nbsp&nbsp&nbsp异常描述 : 抄表册已经完成录入，无法发布数据<br/>
     * @see MeterPlan_PublishPostModel body <br/>
     * @see MeterPlan_PublishGetModel result <br/>
     */ 
    //endregion
    //region 说明 : post
    //发布
    //1.查询抄表计划：
    // 如果抄表计划不存在，抛出异常“抄表计划不存在”；
    //2.验证抄表计划下的抄表册：
    // 如果该抄表计划下不存在状态为“待抄表”或“待复抄”的抄表册，抛出异常“抄表册已经完成录入，无法发布数据”
    //3.发布数据：
    // 根据WorkOrder.id找到该抄表计划下的状态为“待抄表”或“待审核”的抄表工单，如果抄表工单存在，则根据WorkOrder.collectData发布数据，
    // 注意：如果本次表底数大于或等于上次表底数，则发布数据，否则不发布。
    //4.返回信息；
    //endregion
    //region 参数 : post
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌",required = true, dataType = "string", paramType = "header"),

            @ApiImplicitParam(name = "meterPlanId", value = "抄表计划id",required = true, dataType = "string", paramType = "path"),

            @ApiImplicitParam(name = "show", value = "展示形式 one:展示一个,list:展示列表,null(空值):不展示", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "show_info", value = "是否展示详情", defaultValue = "false", required = false, dataType = "boolean", paramType = "query"),

    })
    @ApiImplicitInternalParams({
            @ApiImplicitParam(name = "_token", value = "令牌",required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(name = "_hzhr-user-id", value = "用户编号",required = true, dataType = "int", paramType = "header"),
            @ApiImplicitParam(name = "_hzhr-user-code", value = "用户代码",required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(name = "_hzhr-user-name", value = "用户名",required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(name = "_hzhr-company-id", value = "公司编号",required = true, dataType = "int", paramType = "header"),
            @ApiImplicitParam(name = "_hzhr-dept-id", value = "部门编号",required = true, dataType = "int", paramType = "header"),
            @ApiImplicitParam(name = "_hzhr-user-type", value = "用户类型(关联: common_service.options.code, typeCode = 'USER_TYPE')",required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(name = "_hzhr-transaction-id", value = "交易流水号",required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(name = "_hzhr-transaction-type", value = "交易类型",required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(name = "_hzhr-access-mode", value = "访问模式 0:一般 1:全局",defaultValue = "0", required = false, dataType = "int", paramType = "header"),

            @ApiImplicitParam(name = "_show", value = "展示形式 one:展示一个,list:展示列表,null(空值):不展示", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "_show_info", value = "是否展示详情", defaultValue = "false", required = false, dataType = "boolean", paramType = "query"),

    })
    //endregion
    //region 请求 : post
    @RequestMapping(value = "/meter-plans/{meterPlanId}/publish", method = RequestMethod.POST)
    //endregion
    public MeterPlan_PublishGetModel post(Map<String, String> header,
                                          String meterPlanId,
                                          Map<String, Object> query,
                                          MeterPlan_PublishPostModel body) throws ServiceException {

        /* 查询抄表计划：
            如果抄表计划不存在，抛出异常“抄表计划不存在” */
        RuhujihuaEntityExt ruhujihuaEntityExt = ruhujihuaEntityCustomMapper.selectRuhujihuaAndmeterPlanId(meterPlanId);
        if (ruhujihuaEntityExt == null){
            throw new ServiceException(Meterplan_ErrorsEnum.METERPLAN_PUBLISHSERVICE_POST_201);
        }

        /* 验证抄表计划下的抄表册：
            如果该抄表计划下不存在状态为“待抄表”或“待复抄”的抄表册，抛出异常“抄表册已经完成录入，无法发布数据” */
        int count = cygMapper.select8(ruhujihuaEntityExt.getRhId());
        if (count == 0) {
            throw new ServiceException(Meterplan_ErrorsEnum.METERPLAN_PUBLISHSERVICE_POST_202);
        }

        /* 发布数据：
            根据WorkOrder.id找到该抄表计划下的状态为“待抄表”或“待审核”的抄表工单，如果抄表工单存在，则根据WorkOrder.collectData发布数据，
            注意：如果本次表底数大于或等于上次表底数，则发布数据，否则不发布。 */
        //根据WorkOrder.id找到该抄表计划下的抄表工单
        String id = null;
        String gasUserCode = null;
        String gsaUserName = null;
        String gasUserAddress = null;
        String meterNo = null;
        String collectTime = null;
        String cbjlid = null;

        //根据抄表计划的RH_ID,查询抄表工单
        String rhIds = null;
        String tCollectData = null;
        String tcollectTime = null;
        //抄表工单
        List<ChaobiaogongdanEntityExt> chaobiaogongdanEntityExt = null;
        first:for (WordOrder list : body.getWordOrders()){
            rhIds = ruhujihuaEntityExt.getRhId();
            cbjlid = list.getId();
            tcollectTime = list.getCollectTime();   //采集时间(时间戳)；抄表时间
            if (StringUtils.isEmpty(tcollectTime)) {
                continue;
            }
            tCollectData = list.getCollectData();  //本次表底
            if (tCollectData.equals("")){
                continue first;
            } else {
                tCollectData = new BigDecimal(tCollectData).intValue() + "";
            }

            //抄表工单
            chaobiaogongdanEntityExt = chaobiaogongdanEntityCustomMapper.select1(rhIds,cbjlid,gasUserCode,gsaUserName,gasUserAddress,meterNo);

            //开始更新表底数
            int changeCount = 0;
            //2.2 如果抄表工单存在，则根据WorkOrder.collectData更新该抄表工单的本次表底数
            if (chaobiaogongdanEntityExt.size() != 0) {
                for (ChaobiaogongdanEntityExt chaobiaogongdanEntityExt1 : chaobiaogongdanEntityExt) {
                    //BigDecimal大小比较
                    //        int flag = bigdemical.compareTo(bigdemical1)
                    //        flag = -1,表示bigdemical小于bigdemical1；
                    //        flag = 0,表示bigdemical等于bigdemical1；
                    //        flag = 1,表示bigdemical大于bigdemical1；

                    // 如果本次表底数大于上次表底数，则将该抄表工单的本次抄表情况设置为正常 tCollectData

                    BigDecimal scbd = chaobiaogongdanEntityExt1.getCbjlScbd() != null ? chaobiaogongdanEntityExt1.getCbjlScbd() : new BigDecimal(0);
                    BigDecimal bcyl = new BigDecimal(tCollectData).subtract(scbd);
                    int flag = bcyl.compareTo(new BigDecimal(0));
                    if (flag >= 0) {
                        chaobiaogongdanEntityExt1.setCbjlBcbd(HzhrTypeUtil.string2bigdecimal(tCollectData));
                        chaobiaogongdanEntityExt1.setCbjlCbQk("10");  //10正常
                        chaobiaogongdanEntityExt1.setCbjlSjcbrq(new Date(Long.parseLong(tcollectTime)));
                        chaobiaogongdanEntityExt1.setCbjlBcyqlJs(bcyl);
                        chaobiaogongdanEntityExt1.setCbjlBcyql(bcyl);
                        chaobiaogongdanEntityExt1.setCbjlJcQk(null);
                    } else {//如果本次表底小于上次表底数，不发布数据
                        continue;
                    }

                    chaobiaogongdanEntityMapper.updateByPrimaryKeySelective(chaobiaogongdanEntityExt1);
                }

            }

        }

        /* 4.返回信息 */
        MeterPlan_PublishGetModel result = new MeterPlan_PublishGetModel();
        return result;
    }


}
